import { useEffect, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import TagCrowdGroupDrawer from '../components/TagCrowdGroupDrawer';
import TagGroupDrawer from '../components/TagGroupDrawer';
import { currentDimSelector } from '../selector/dimSelector';

// 输入 dim ID, 输出 drawer 组件
const useDimTagList = (props) => {
  const { dimId, setSelectedDimId, groupTagItem } = props;
  const dispatch = useDispatch();
  // 所有已浏览过的标签列表(id:[children])
  const groupTag = useSelector((state) => state.label.groupTag);
  // 即将添加到购物车的标签信息
  const currentGroupTagInfo = useSelector((state) =>
    currentDimSelector(state, dimId),
  );
  // 当前已选择的按钮的标签列表
  const currentGroupTagChildren = groupTag[dimId];
  useEffect(() => {
    if (dimId) {
      dimId && typeof dimId === 'string'
        ? ''
        : dispatch({ type: 'label/loadGroupTag', payload: { dimId } });
    }
  }, [dimId, dispatch]);

  const drawerComponent = useMemo(() => {
    return (
      <>
        {/* dimId 若为 string 则展示已有人群弹窗 */}
        {typeof dimId === 'string' ? (
          <TagCrowdGroupDrawer
            handleCloseDrawer={() => setSelectedDimId(null)}
            crowdKey={dimId}
            propsGroupTagInfo={groupTagItem}
          />
        ) : (
          <TagGroupDrawer
            currentGroupTagChildren={currentGroupTagChildren}
            currentGroupTagInfo={currentGroupTagInfo}
            handleCloseDrawer={() => setSelectedDimId(null)}
            dimId={dimId}
            propsGroupTagInfo={groupTagItem}
          />
        )}
      </>
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    currentGroupTagChildren,
    currentGroupTagInfo,
    setSelectedDimId,
    groupTagItem,
    dimId,
  ]);

  return {
    drawerComponent,
  };
};

export default useDimTagList;
